package servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;


@WebServlet("/download")
public class DownloadServlet extends HttpServlet {

    private static final long serialVersionUID = 815029025679527280L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String filepath = req.getParameter("filepath");
        String filename = req.getParameter("filename");
        byte[] bytes = filename.getBytes("UTF-8");

        try {
            filename = new String(bytes,"ISO8859-1");
            resp.setHeader("content-disposition", "attachment; filename="+filename);
            InputStream is = this.getServletContext().getResourceAsStream(filepath);
            ServletOutputStream os = resp.getOutputStream();
            int len = -1;
            byte[] buf = new byte[1024];
            while((len = is.read(buf)) != -1) {
                os.write(buf,0, len);
            }
            //关闭流
            os.close();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
